package com.xiaoyu.lanling.router.deeplink;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.xiaoyu.base.data.UserData;
import com.xiaoyu.lanling.router.Router;

import java.util.concurrent.atomic.AtomicReference;

import in.srain.cube.util.CLog;
import in.srain.cube.util.CheckUtil;

class DeepLinkDispatcher {

    private static final String TAG = "DeepLinkDispatcher";

    private final DeepLinkLoader mLoader;
    private final AtomicReference<DeepLinkEntry> mPendingEntry = new AtomicReference<>();

    DeepLinkDispatcher(DeepLinkLoader loader) {
        this.mLoader = loader;
    }

    boolean dispatch(@NonNull Context context, @NonNull Uri uri, @Nullable Intent sourceIntent) {
        CheckUtil.checkNotNull(context, "context cannot be null");
        CheckUtil.checkNotNull(uri, "uri cannot be null");

        DeepLinkEntry entry = mLoader.findEntry(uri);
        if (entry == null) {
            CLog.i(TAG, "entry not find: %s", uri);
            return false;
        }
        dispatchEntry(context, entry, sourceIntent);
        return true;
    }

    void dispatchPending(@NonNull Context context, @NonNull Uri uri) {
        DeepLinkEntry entry = mLoader.findEntry(uri);
        if (entry == null) {
            CLog.i(TAG, "entry not find: %s", uri);
            return;
        }
        mPendingEntry.set(entry);
        CLog.i(TAG, "dispatch pending: %s", entry);
    }

    private void dispatchEntry(Context context, DeepLinkEntry entry, Intent sourceIntent) {
        CLog.i(TAG, "dispatchEntry entry: %s", entry);
        if (tryDispatchToLogin(entry)) {
            return;
        }
        startActivity(context, entry, sourceIntent);
    }

    private boolean tryDispatchToLogin(DeepLinkEntry entry) {
        if (!entry.needLogin || UserData.getInstance().hasLogin()) {
            return false;
        }
        mPendingEntry.set(entry);
        Router.Companion.getInstance().gotoLoginActivity();
        CLog.i(TAG, "dispatchEntry to login: %s", entry);
        return true;
    }

    void tryDispatcherPendingEntry(Context context) {
        final DeepLinkEntry pendingEntry = mPendingEntry.getAndSet(null);
        if (pendingEntry != null) {
            CLog.i(TAG, "dispatch pending entry: %s", pendingEntry);
            dispatchEntry(context, pendingEntry, null);
        }
    }

    private static void startActivity(Context context, DeepLinkEntry entry, Intent sourceIntent) {
        Intent newIntent = entry.buildIntent(context);
        if (sourceIntent != null) {
            newIntent.setAction(sourceIntent.getAction());
            newIntent.addFlags(sourceIntent.getFlags());
        }
        context.startActivity(newIntent);
    }
}
